<?php
/**
 * Created by PhpStorm.
 * User: JSQ-SL
 * Date: 2018/10/19
 * Time: 15:58
 */

namespace app\index\controller;

use app\index\base_controller\BaseController;
use app\index\table\FurnAlterTable;
use app\index\table\FurnTable;
use think\Db;
use think\Exception;

class Furn extends BaseController
{
    public function furnTest(){
        $data = FurnTable::table()->find();
        dump($data);
    }

    public function furnList() {
        return $this->fetch('furn_list');
    }

    public function getFurnList() {
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $order = input('order');
        $sortStr = "$sort $order";
        if(empty($sort)){
            $sortStr = 'FURN_NO desc';
        }

        $condition = FurnTable::getSessionConditions();
        try{
            $listSql = FurnTable::table()->where($condition)->order($sortStr)->limit($offset,$limit)->fetchSql()->select();
            $list = Db::query($listSql);
            $totalSql = FurnTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            return ['rows'=>$list,'total'=>$total[0]['TP_COUNT']];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    public function addPage() {
        $this->assign('data',null);
        $this->view->engine->layout('layout_popup');
        return $this->fetch('furn_add');
    }

    public function addFurn() {
        $data = input();
        try {
            FurnTable::add($data);
            return json_encode(['code'=>'200','msg'=>'操作成功']);

        } catch (Exception $e) {
            return json_encode(['code'=>'0','msg'=>'操作失败：'.$e->getMessage()]);
        }
    }

    public function editPage() {
        $furnNo = input('furnNo');
        $data = FurnTable::get($furnNo);
        if(empty($data)){
            return '查询家具信息失败';
        }
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return $this->fetch('furn_edit');
    }

    public function editFurn() {
        $furnNo = input('FURN_NO');

        $old = FurnTable::get($furnNo);
        if (empty($old)) {
            return json_encode(['code'=>'0','msg'=>'查询家具信息失败','data'=>input()]);
        }

        $data = input();
        try {
            FurnTable::update(['FURN_NO'=>$furnNo],$data);
            return json_encode(['code'=>'200','msg'=>'操作成功']);

        } catch (Exception $e) {
            return json_encode(['code'=>'0','msg'=>'操作失败：'.$e->getMessage()]);
        }
    }

    /**
     * 批量删除
     */
    public function deleteAll(){
        $list = input('list');
        Db::startTrans();
        try{
            foreach ($list as $furnNo){
                FurnTable::delete(['FURN_NO'=>$furnNo]);
            }
            Db::commit();
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            Db::rollback();
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }



    /**
     * page--高级查询
     */
    public function searchPage(){
        $this->assign('data',null);
        $this->view->engine->layout('layout_popup');
        return view('furn_search');
    }

    /**
     * 新增变动页面
     */
    public function addAlterPage(){
        $idStr = input('idList');
        $furnList = FurnTable::table()->where([['FURN_NO','in',$idStr]])->select();
        if(empty($furnList)){
            return '查询家具信息失败';
        }
        $this->assign('furnIds',$idStr);
        $this->assign('furnList',$furnList);
        $this->view->engine->layout('layout_popup');
        return view('furn_alter_add');
    }

    /**
     * 新增变动
     */
    public function addAlter(){

        $furnIds = input('furnIds');
        $alterType = input('ALTERTYPE_ID');
        $furnArr = explode(',',$furnIds);
        if(!in_array($alterType,['01','02'])){
            return json_encode(['code'=>'0','msg'=>'非法参数']);
        }

        try{
            $preAlterNo = FurnAlterTable::getPreAlterInfoNo();
            Db::startTrans();
            foreach ($furnArr as $furnNo){
                $furn = FurnTable::get($furnNo);
                if(empty($furn)){
                    Db::rollback();
                    return json_encode(['code'=>'0','msg'=>"查询家具[$furnNo]失败"]);
                }

                if($alterType == '01'){
                    //调拨
                    FurnAlterTable::add([
                        'PRE_ALTERINFO_NO'=>$preAlterNo
                        ,'FURN_NO'=>$furnNo
                        ,'ALTERTYPE_ID'=>$alterType
                        ,'ALTER_TIME'=>input('ALTER_TIME')
                        ,'CHECK_PERSON'=>input('CHECK_PERSON')
                        ,'CHARGE_PERSON'=>input('CHARGE_PERSON')
                        ,'REMARK'=>input('REMARK')
                        ,'DEPARTNEW_ID'=>$furn['DEPART_ID']
                    ]);

                    FurnTable::update(['FURN_NO'=>$furnNo],['DEPART_ID'=>input('DEPART_ID')]);
                }
                if($alterType == '02'){
                    //报废
                    FurnAlterTable::add([
                        'PRE_ALTERINFO_NO'=>$preAlterNo
                        ,'FURN_NO'=>$furnNo
                        ,'ALTERTYPE_ID'=>$alterType
                        ,'ALTER_TIME'=>input('ALTER_TIME')
                        ,'CHECK_PERSON'=>input('CHECK_PERSON')
                        ,'CHARGE_PERSON'=>input('CHARGE_PERSON')
                        ,'DISPOSE_DIRECT'=>input('DISPOSE_DIRECT')
                        ,'REMARK'=>input('REMARK')
                    ]);
                    FurnTable::update(['FURN_NO'=>$furnNo],['STATE_ID'=>'02']);
                }
            }
            Db::commit();
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            Db::rollback();
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * action 批量删除变动信息
     */
    public function deleteAlter(){
        $list = input('list');
        Db::startTrans();
        try{
            foreach ($list as $alterNo){
                FurnAlterTable::delete(['ALTER_NO'=>$alterNo]);
            }
            Db::commit();
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            Db::rollback();
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * page--变动信息
     */
    public function furnAlterList(){
        return view('furn_alter_list');
    }

    /**
     * action--获取变动信息
     */
    public function getFurnAlterList(){
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $order = input('order');
        $sortStr = "$sort $order";
        if(empty($sort)){
            $sortStr = 'fa.ALTER_NO desc';
        }

        $condition = null;
        $listCondition = Login::getListConditionFurnAlter();
        if (!empty($listCondition['FURN_NO'])) {
            $value = $listCondition['FURN_NO'];
            $condition[] = ['fa.FURN_NO','like',"$value%"];
        }
        if (!empty($listCondition['ALTER_NO'])) {
            $value = $listCondition['ALTER_NO'];
            $condition[] = ['fa.ALTER_NO','like',"$value%"];
        }
        if (!empty($listCondition['ALTERTYPE_ID'])) {
            $value = $listCondition['ALTERTYPE_ID'];
            $condition[] = ['fa.ALTERTYPE_ID','=',$value];
        }
        if (!empty($listCondition['ALTER_TIME_START'])) {
            $value = Db::raw("to_date('{$listCondition['ALTER_TIME_START']}','yyyy-mm-dd')");
            $condition[] = ['fa.ALTER_TIME','>=',$value];
        }
        if (!empty($listCondition['ALTER_TIME_END'])) {
            $value = Db::raw("to_date('{$listCondition['ALTER_TIME_END']}','yyyy-mm-dd')");
            $condition[] = ['fa.ALTER_TIME','<=',$value];
        }

        try{
            $listSql = FurnAlterTable::table()->where($condition)->order($sortStr)->limit($offset,$limit)->fetchSql()->select();
            $list = Db::query($listSql);
            $totalSql = FurnAlterTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            return ['rows'=>$list,'total'=>$total[0]['TP_COUNT']];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * page--变动高级查询
     */
    public function alterSearchPage(){
        $this->view->engine->layout('layout_popup');
        return view('furn_alter_search');
    }

    /**
     * page--新增变动
     */
    public function alterDetailPage(){
        $alterNo = input('alterNo');
        $data = FurnAlterTable::get($alterNo);
        if(empty($data)){
            return '查询变动信息失败';
        }
        $preNo = $data['PRE_ALTERINFO_NO'];
        $list = FurnAlterTable::table()->where(['PRE_ALTERINFO_NO'=>$preNo])->select();
        $this->assign('list',$list);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('furn_alter_detail');
    }


    /**
     * 打印
     */
    public function printPage() {
        $id = input('id');
        $data = FurnTable::get($id);
        if(empty($data)){
            return '查询家具信息失败';
        }
        $config = FurnTable::getConfigPrint();
        $this->assign('config',$config);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('furn_print');
    }

    public function addConditionSession() {
        $condition = input();
        Login::setListConditionFurn($condition);
        return json_encode(['code'=>'200']);
    }
      public function addSessionAlter() {
        $condition = input();
        Login::setListConditionFurnAlter($condition);
        return json_encode(['code'=>'200']);
    }

    public function importPage() {
        $this->view->engine->layout('layout_popup');
        return view('import');
    }

    public function import() {
        $inputData = input('data');
        $postData = base64_decode($inputData);
        $list = json_decode($postData,true);
        $start = input('start');

        Db::startTrans();
        $fieldList = FurnTable::FURN_FIELD_LIST;
        $fieldCount = count($fieldList);
        foreach ($list as $key => $row) {
            $data = [];

            // 字段赋值
            $i = 0;
            foreach ($row as $key1=>$value) {
                $data[$fieldList[$i]] = $value;
                $i++;
                if ($i>=$fieldCount) {
                    break;
                }
            }

            try{
                FurnTable::addImport($data);
            }
            catch (Exception $e){
                Db::rollback();
                return json_encode(['code'=>'0','msg'=>"第".($key + $start)."行数据写入出错",'data'=>$e->getMessage()]);
            }
        }

        Db::commit();
        return json_encode(['code'=>'200','msg'=>'导入成功']);
    }

    /**
     * page 家具导出页面
     */
    public function exportExcelPage() {
        $condition = FurnTable::getSessionConditions();

        try{
            $totalSql = FurnTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            $total = $total[0]['TP_COUNT'];
            $this->assign('total',$total);

            $arr = $this->getDownLoadList($total);
            $this->assign('downList',$arr);

            $this->view->engine->layout('layout_popup');
            return view('export_excel');
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * action 家具导出Excel
     */
    public function exportExcel(){
        $sortStr = 'F.FURN_NO desc';
        $start = input('start');
        $startL = $start-1;
        $end = input('end');
        $endL = $end-$start+1;

        $condition = FurnTable::getSessionConditions();

        try{
            $listSql = FurnTable::table()->where($condition)->limit($startL,$endL)->order($sortStr)->fetchSql()->select();
            $list = Db::query($listSql);
            FurnTable::exportExcel($list,"家具$start-$end");
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }



}